package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> queryBlogUser(blog));
        return Result.ok(records);
    }

    @Override
    public Result queryById(Long id) {
        // 1. 查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("不存在");
        }
        queryBlogUser(blog);
        return Result.ok(blog);
    }

    private static final DefaultRedisScript<Long> LIKE_BLOG_SCRIPT;

    static {
        LIKE_BLOG_SCRIPT = new DefaultRedisScript<>();
        LIKE_BLOG_SCRIPT.setLocation(new ClassPathResource("likeBlog.lua"));
        LIKE_BLOG_SCRIPT.setResultType(Long.class);
    }

    @Override
    public Result likeBlog(Long id) {
        Long userId = UserHolder.getUser().getId();
        Long result = stringRedisTemplate.execute(LIKE_BLOG_SCRIPT, Collections.emptyList(), id.toString(), userId.toString());
        if (result.intValue() == 0) {
            // 取消点赞
            this.update().setSql("liked = liked - 1").eq("id", id).update();
            return Result.ok(false);
        } else {
            // 点赞
            this.update().setSql("liked = liked + 1").eq("id", id).update();
            return Result.ok(true);
        }
    }

    @Override
    public Result queryBlogLikes(Long id) {
        Set<String> range = stringRedisTemplate.opsForZSet().range("like:blog:" + id, 0, 5);
        List<Long> top5UserIds = range.stream().map(Long::valueOf).collect(Collectors.toList());
        if (top5UserIds == null || top5UserIds.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        Stream<UserDTO> users = userService
                .query()
                .in("id", top5UserIds)
                .last("order by field(id," + (StrUtil.join(",", top5UserIds)) + ")")
                .list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class));
        return Result.ok(users);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 1. 获取登录用户
        Long userId = UserHolder.getUser().getId();
        blog.setUserId(userId);
        // 2. 保存探店笔记
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("保存笔记失败");
        }
        // 3. 查询笔记作者的所有粉丝
        LambdaQueryWrapper<Follow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Follow::getFollowUserId, userId);
        List<Follow> follows = followService.list(queryWrapper);
        for (Follow follow : follows) {
            // 4. 将笔记id推送给粉丝
            Long id = follow.getUserId();
            String key = "feed:" + id;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 5. 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOgFollow(Long max, Integer offset) {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2. 查询收件箱
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().rangeByScoreWithScores("feed:" + userId, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 3. 解析数据
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            ids.add(Long.valueOf(tuple.getValue()));
            long time = tuple.getScore().longValue();
            if (minTime == time) {
                os++;
            } else {
                os = 1;
                minTime = time;
            }
        }
        // 4. 封装返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        List<Blog> list = query().in("id", ids).last("ORDER BY FIELD(id," + StrUtil.join(",", ids) + ")").list();
        for (Blog blog : list) {
            queryBlogUser(blog);
            setIsLiked(blog);
        }
        scrollResult.setList(list);
        return Result.ok(scrollResult);
    }


    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        setIsLiked(blog);
    }

    private void setIsLiked(Blog blog) {
        if (UserHolder.getUser() == null) {
            blog.setIsLike(false);
            return;
        }
        String blogKey = "like:blog:" + blog.getId().toString();
        String userId = UserHolder.getUser().getId().toString();
        // 检查用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(blogKey, userId);
        blog.setIsLike(score != null);
    }
}
